<?php
require_once('../nabtonServer/dataManager/definitions.php');
require_once('../nabtonServer/dataManager/DataManager.php');

define ("DEBUG_MODE", "off", true);

//==============================================================================
//Class DataManager
//==============================================================================
class DataCollector
{

	private $username_;
	private $password_;
	private $server_;  
	private $dbName_;  
	private $mysqli_; 
	private $isDbOpen_;

	public function __construct($user, $pass, $server, $dbName)
	{
		//echo "-NB_DATABASE_COLLECTOR created \n";
		$this->username_   = $user;
		$this->password_   = $pass;
		$this->server_     = $server;
		$this->dbName_     = $dbName;
		$this->isDbOpen_   = false;
	}

	public function __destruct()
	{
		$this->closeDataBase();
		if(DEBUG_MODE == 'on')echo "-DataManager destroyed \n";
	}

	public function openDataBase()
	{
		//echo "-Opening database\n";

		$this->mysqli_ = new mysqli($this->server_,
									$this->username_,
									$this->password_,
									$this->dbName_);
		if ($this->mysqli_->connect_error) 
		{
			if(DEBUG_MODE == 'on')echo "-Problem opening database\n";
		}
		else
		{
			$this->isDbOpen_ = true;
		}
	}

	public function closeDataBase()
	{
		if(DEBUG_MODE == 'on')echo "-Closeing database\n ";
		$this->mysqli_->close();
	}

	public function insertData($sid, $data)
	{	
		if ($this->isDbOpen_)
		{
			$tableName = NB_COLLECTOR_TABLE_DATA_PREFIX . $sid;
			$doesTableExist = $this->mysqli_->query("SELECT 1 FROM $tableName");

			if ($doesTableExist)
			{
				if(DEBUG_MODE == 'on')echo "Sid is ok! \n";
			    $param = NB_COLLECTOR_DATA_COLUMN_VALUE;
				$this->mysqli_->query("INSERT INTO $tableName ($param) VALUES ($data)");

				return true;
			}
			else
			{
				if(DEBUG_MODE == 'on')echo "Sid does not exists! \n";
				
			}
		}
		else
		{
			if(DEBUG_MODE == 'on')echo "-Database is not open. Data not added!\n";

		}
		return false;
	}


}


function getControlMessage($sid) {
 
	$dbM = new DataManager   ("root", "amazon", "localhost", NB_DATABASE_CONTROL);
	$dbM->selectAllFromTable(NB_CONTROL_TABLE_COMMANDS,
							 NB_CONTROL_COMMANDS_COLUMN_SID."="."$sid AND ".
							 NB_CONTROL_COMMANDS_COLUMN_STATUS."="."'new'"); //TODO add enum table for new, etc..

	$numRes = $dbM->retrieveNumberOfResults();

	if($numRes>0)
	{
		while($data = $dbM->retrieveResult())
		{
		    echo $data[NB_CONTROL_COMMANDS_COLUMN_COMMAND]."\n";
		}

		//Update status to "executed"
		$columns = array(NB_CONTROL_COMMANDS_COLUMN_STATUS);
		$values  = array("executed");
		$dbM->updateRow(NB_CONTROL_TABLE_COMMANDS, $columns, $values, 
						NB_CONTROL_COMMANDS_COLUMN_SID."="."$sid AND "
						.NB_CONTROL_COMMANDS_COLUMN_STATUS."="."'new'");
	}
}


//==============================================================================
// Main program
//==============================================================================

//Verify data
//if(isset($_GET['sid']) && isset($_GET['data']))

if(isset($_GET['mid']) && isset($_GET['sid']))
{

	//Data from request
	$mid  = $_GET["mid"];
	if(!$mid)$mid = NABTON_DATA;
	
	$sid  = $_GET["sid"];
	$dbM = new DataManager   ("root", "amazon", "localhost", NB_DATABASE_ADMIN);
	$dbM->selectAllFromTable(NB_ADMIN_TABLE_STREAMS,
							 NB_ADMIN_STREAMS_COLUMN_SID."=".$sid); 

	$numRes = $dbM->retrieveNumberOfResults();
	if($numRes == 1)
	{
		if ($data = $dbM->retrieveResult())
		{
			if($mid == NABTON_DATA)
			{
				   //Get Data
				   $dd = $_GET["data"];
		    	   $dbC = new DataCollector ("root", "amazon", "localhost", NB_DATABASE_COLLECTOR);
				   $dbC->openDataBase();
				   $success = $dbC->insertData($sid, $dd);
	               echo "$mid $sid ";
		    }
			if($mid == NABTON_INFO)
			{
				$file = "info-".$sid.".nabton";
				$info = $_GET["info"]; 
				file_put_contents($file, $info);
			    echo "$mid $sid ";
			}
			if($mid == NABTON_VOID)
			{	
				// Do nothing	    	
			}	
			    		    
		    //Return control message if any
		    getControlMessage($sid);
		}
	}
}
else
{
	if(DEBUG_MODE == 'on')echo "- Not a valid request, die \n";
	die();
}

?>
